<?php

namespace addons\booking\model;

use think\Model;


class OrderCalendar extends Model
{

    // 表名
    protected $name = 'booking_order_calendar';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'reserve_time_text'
    ];


    public function getReserveTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['reserve_time']) ? $data['reserve_time'] : '');
        return is_numeric($value) ? date("Y-m-d", $value) : $value;
    }

    protected function setReserveTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    /**
     * 判断时间范围是否有已预订
     * @param int $house_id
     * @param string $start_time
     * @param string $end_time
     * @return boolean
     */
    public static function isHasBooked($house_id, $start_time, $end_time)
    {
        $startTime = is_numeric($start_time) ? $start_time : strtotime($start_time);
        $endTime = is_numeric($end_time) ? $end_time : strtotime($end_time);
        //不包含离开时间，离开可以有人
        return self::where('house_id', $house_id)->where('status', 'normal')->where('reserve_time', '>=', $startTime)->where('reserve_time', '<', $endTime)->count();
    }

    /**
     * 根据时间加入已预订记录
     *
     * @param int $user_id
     * @param int $house_id
     * @param string $orderid
     * @param string $start_time
     * @param string $end_time
     * @return void
     */
    public static function addCalendar($user_id, $house_id, $orderid, $start_time, $end_time)
    {
        $startTime = is_numeric($start_time) ? $start_time : strtotime($start_time);
        $endTime = is_numeric($end_time) ? $end_time : strtotime($end_time);
        $data = [];
        $time = 24 * 60 * 60;
        //第一天为开始，最后一天已离去，不计算
        for ($i = $startTime; $i < $endTime; $i += $time) {
            $data[] = [
                'user_id'      => $user_id,
                'house_id'     => $house_id,
                'orderid'      => $orderid,
                'reserve_time' => $i
            ];
        }
        (new self)->saveAll($data);
    }

    /**
     * 订单的取消，退款，修改状态
     *
     * @param string $orderid
     * @return void
     */
    public static function editCalendar($orderid)
    {
        (new self)->where('orderid', $orderid)->update(['status' => 'canceled', 'updatetime' => time()]);
    }
}
